package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.leaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.utils.SMSUtils;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
        @Autowired
        private UserInfoService userInfoService;

    //获取短信验证码
    @Override
    public void sendMessage(String phone) {
        //生成6位随机数字作为验证码
        String code = RandomStringUtils.randomNumeric(6);
        //调用发送短信的工具类，发送短信
        SMSUtils.send(code,phone);

        //3.将生成的验证码保存在redis中，用统一的前缀+手机号，作为唯一的key
        stringRedisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX+phone,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    //登录功能
    @Override
    public String login(LoginVo loginVo) {
        //获取前端的手机号码和短信验证码code
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //校验phone和code是否为空
        if (!StringUtils.hasText(phone)) {
            throw new leaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        } else if (!StringUtils.hasText(code)) {
            throw new leaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        } else {
            //根据phone从redis中查询验证码，但存储的key是前缀＋手机号
            // 若结果为空，则验证码已过期
            String key = RedisConstant.APP_LOGIN_PREFIX+phone;
            String value = stringRedisTemplate.opsForValue().get(key);
            if (value == null) {
                throw new leaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
            }
            //比较前端发送的验证码和从redis中查出来的验证码，若不同则验证码错误
            if (!code.equalsIgnoreCase(value)) {
                throw new leaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
            }

            //根据phone从数据库中查询用户信息

            UserInfo one = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
            if (one == null) {
                //表示数据库中没有该用户，那么创建新用户，并将该用户存储到数据库
                UserInfo userInfo = new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(BaseStatus.ENABLE);
                userInfo.setNickname("用户"+phone.substring(5));
                userInfoService.save(userInfo);
            }
            //判断用户是否被禁用,0表示被禁用
            if (one.getStatus().getCode() == 0) {
                throw new leaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
            }
            //使用JWT工具生成token
            String token = JwtUtil.createToken(one.getId(), one.getPhone());

            return token;
        }
    }

    //获取登录用户的个人信息
    @Override
    public UserInfoVo getUserInfoVo(Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());

        return userInfoVo;
    }
}
